<!-- 角色编辑弹窗 -->
<template>
  <div>
    <el-drawer :visible="drawerEditBoolen"
               size="50%"
               :before-close="handleClose"
               ref="drawer">
      <template v-slot:title>
        <span class="hLabel">{{ isUpdate ? '修改门店' : '添加门店' }}</span>
      </template>
      <div class="ele-body">
        <el-card shadow="never">
          <div class="flex-column-between height83">
            <el-form ref="form"
                     :model="form"
                     :rules="rules"
                     label-width="100px">
              <el-form-item label="门店名称:"
                            prop="name">
                <el-input clearable
                          v-model="form.name"
                          placeholder="请输入门店名称">
                </el-input>
              </el-form-item>
              <el-form-item label="门店账号:"
                            prop="account">
                <el-input clearable
                          v-model="form.account"
                          placeholder="请输入门店账号">
                </el-input>
              </el-form-item>

              <el-form-item label="姓名:"
                            prop="real_name">

                <el-input clearable
                          v-model="form.real_name"
                          placeholder="请输入门店联系人姓名" />
              </el-form-item>
              <el-form-item label="手机号:"
                            prop="phone">

                <el-input clearable
                          type="number"
                          :maxlength="11"
                          v-model="form.phone"
                          placeholder="请输入手机号" />
              </el-form-item>
              <el-form-item v-if="!isUpdate"
                            label="门店密码:"
                            prop="password">

                <el-input clearable
                          type="number"
                          v-model="form.password"
                          placeholder="请输入门店密码" />
              </el-form-item>

              <el-form-item v-if="!isUpdate"
                            label="角色:">

                <role-select v-model="form.role_id" />

              </el-form-item>

              <!-- 提交图片 -->
              <el-form-item label="店铺门头照:"
                            prop="logo">
                <el-upload action="#"
                           :on-exceed="exceedFn"
                           list-type="picture-card"
                           :file-list="fileList"
                           :limit="1"
                           :on-change="
					  (files, fileList) => handleFileChange(files, fileList)
					"
                           :auto-upload="false">
                  <i slot="default"
                     class="el-icon-plus"></i>
                  <div slot="file"
                       slot-scope="{ file }">
                    <img class="el-upload-list__item-thumbnail"
                         :src="file.url"
                         alt="" />
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-preview"
                            @click="handlePictureCardPreview()">
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <span class="el-upload-list__item-delete"
                            @click="handleDownload(file)">
                        <i class="el-icon-download"></i>
                      </span>
                      <span class="el-upload-list__item-delete"
                            @click="handleRemove(file)">
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>
              </el-form-item>
              <el-form-item label="导航地址:"
                            prop="navigation">

                <el-input v-model="form.navigation"
                          placeholder="请输入地址"
                          @focus="selPosition"
                          clearable />
              </el-form-item>
              <el-form-item label="选择地址:">

                <regions-select v-model="city"
                                @input="getAddressResultObj"
                                placeholder="请选择省市区" />
              </el-form-item>

              <el-form-item label="详情地址:"
                            prop="address">

                <el-input type="textarea"
                          resize="none"
                          placeholder="请输入详情地址"
                          v-model="form.address"
                          maxlength="30"
                          show-word-limit></el-input>
              </el-form-item>

            </el-form>
            <div class="drawer__footer">
              <el-button round
                         type="plain"
                         @click="handleClose"
                         size="medium">返回</el-button>
              <el-button type="primary"
                         round
                         :loading="loading"
                         size="medium"
                         @click="save">确定</el-button>
            </div>
          </div>
        </el-card>
      </div>
    </el-drawer>
    <!-- 图片预览 -->
    <el-image-viewer v-if="viewerVisible"
                     style="z-index: 9999"
                     :on-close="closeViewer"
                     :url-list="imgViewArr" />
    <position ref="pos"
              @chooseMapPoint="getCallMap"
              @cancel="cancelMap"
              @sure="sure"></position>
  </div>
</template>
  
  <script>
import position from './map.vue';
import RoleSelect from './role-select.vue';
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
import RegionsSelect from '@/components/RegionsSelect/index.vue';
// import {
//   userOssSignature,
//   qnyOssSignature
// } from '@/api/creatCenter/material';
// import { storageConfigDetail } from '@/api/storageInfo/index';

// import axios from 'axios';
// import {
//   siteCategoriesInsert,
//   siteCategoriesList,
//   siteCategoriesModify,
//   siteCategoriesDetail
// } from '@/api/serviceManagement/categoriesList';
import { getRegionLabel } from 'ele-admin/packages/utils/regions';
import { upload } from '@/api/saveImg/index'
import { addStore, editStore } from '@/api/store/index'

export default {
  name: 'pictureEdit',
  components: { ElImageViewer, RegionsSelect, RoleSelect, position },
  props: {
    drawerEditBoolen: {
      type: Boolean,
      default: false
    },
    // 修改回显的数据
    data: Object
  },
  data () {
    const categoryImage = (rule, value, callback) => {
      console.log(this.form.logo);
      if (!this.form.logo) {
        callback(new Error('请上传图片'));
      } else {
        callback();
      }
    };
    const DEFAULT_FORM = {
      // 店铺名字
      name: '',
      // 手机号
      phone: '',
      // 省id
      province_id: '',
      // 区id
      county_id: '',
      // 市id
      city_id: '',
      // 省
      province_name: '',
      // 市
      city_name: '',
      // 区
      county_name: '',
      // 详细地址
      address: "",
      // 角色id
      role_id: '',
      // 密码
      password: '',
      // 姓名
      real_name: '',
      // 门店账号
      account: '',
      //logo图
      logo: '',
      longitude: '',
      dimension: '',
      navigation: '',
    };
    return {
      address: '',
      city: ['140000', '140400', '140425'],
      storageMode: 2,
      options: [],
      imageUrl: '',
      imgViewArr: [],
      viewerVisible: false,
      // 表单数据
      form: { ...DEFAULT_FORM },
      dialogImageUrl: '',
      fileList: [],
      dialogVisible: false,
      // 表单验证规则
      rules: {
        name: [
          {
            required: true,
            message: '请输入店铺名字',
            trigger: 'blur'
          }
        ],

        real_name: [
          {
            required: true,
            message: '请输入门店联系人姓名',
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          }
        ],
        account: [{
          required: true,
          message: '请输入门店账号',
          trigger: 'blur'
        }],
        password: [{
          required: true,
          message: '请输入门店密码',
          trigger: 'blur'
        }],
        address: [{
          required: true,
          message: '请输入详情地址',
          trigger: 'blur'
        }],
        navigation: [{
          required: true,
          message: '请输入导航地址',
          trigger: 'blur'
        }],

        // 站点 图片上传
        logo: [
          { required: true, validator: categoryImage, trigger: 'change' }
        ]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      showChoose: false
    };
  },
  activated () {

  },
  methods: {
    selPosition () {
      this.$nextTick(() => {
        console.log(this.$refs['pos']);
        if (this.isUpdata) {
          this.$refs['pos'].show(this.form)
        } else {
          this.$refs['pos'].show()
        } // 视频号二维码展示
      });
    },
    sure (e) {
      // console.log(e);
      console.log(e);
      this.form.longitude = e.lat;
      this.form.dimension = e.lng;
      this.form.navigation = e.address;
    },
    // 地图 取消
    cancelMap () {

    },
    getAddressResultObj (value, nameCode) {
      console.log(value, nameCode)

      const regionLabel = getRegionLabel(value);
      console.log(regionLabel)
      this.form.city_name = regionLabel[1]
      this.form.city_id = value[1]
      this.form.county_name = regionLabel[2]
      this.form.county_id = value[2]
      this.form.province_name = regionLabel[0]
      this.form.province_id = value[0]
    },
    // 关闭查看器
    closeViewer () {
      this.viewerVisible = false;
    },
    // 下载图片
    handleDownload (file) {
      window.open(file.url);
    },
    // 删除图片
    handleRemove () {
      this.fileList = [];
      this.imageUrl = '';
    },
    //  图片上传个数超过限制
    exceedFn () {
      this.$message({
        message: '图片上传已达到上限,请删除后再上传',
        type: 'warning'
      });
    },
    // 关闭抽屉
    handleClose () {
      console.log('查看详情');
      this.$emit('update:drawerEditBoolen', false);
    },
    async handleFileChange (file) {

      this.aliFn(file)
    },
    // 阿里云
    async aliFn (file) {
      this.loading = true;

      let files = file.raw;

      console.log(files)
      // 构建请求参数
      let params = new FormData();
      console.log(params);

      //   params.append('signature', '132321313');
      params.append('file', files);
      console.log(params);

      //   let config = {
      //     headers: {
      //       'Access-Control-Allow-Origin': '*',
      //       'x-oss-callback-Authorization': getToken()
      //     }
      //   };

      const res = await upload(params);
      //   let result = await axios.post(res.host, param, config);
      //   let url = res.host + '/' + date + suffix;
      console.log(res);
      if (res.code == 0) {
        this.form.logo = res.data.url
        this.loading = false;
      }
      //   this.form.categoryImages = url;
      //   this.imageUrl = url;
      //   this.loading = false;
    },

    /* 保存编辑 */
    save () {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return false;
        }
        // if (this.isUpdate) {
        //   this.form.logo = this.imageUrl;
        // }
        const data = {
          ...this.form
        };
        console.log(data);
        this.loading = true;
        const reslIst = this.isUpdate ? editStore : addStore

        reslIst(data)
          .then((msg) => {
            console.log(msg);
            this.loading = false;
            this.$message.success(msg.msg);

            this.handleClose();
            this.$emit('done');
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.msg);
          });
      });
    }
    /* 更新visible */
  },
  watch: {
    drawerEditBoolen (visible) {
      this.$nextTick(() => {
        if (visible) {
          console.log(this.data);
          if (this.data) {
            this.form.id = '';
            this.$util.assignObject(this.form, {
              ...this.data
            });
            this.city = []
            this.city[0] = String(this.form.province_id)
            this.city[1] = this.form.city_id.toString()
            this.city[2] = this.form.county_id.toString()
            const newArr = this.city.map(str => {
              if (str.length < 6) {
                return str.padEnd(6, '0'); // 使用 padEnd 在字符串末尾补零，直到长度为 6
              } else {
                return str.substring(0, 6); // 只取字符串的前 6 位
              }
            });
            console.log(newArr)
            this.city = newArr
            if (this.form.logo) {
              this.imageUrl = this.form.logo;
              let markIndex = this.form.logo.lastIndexOf('.');
              let suffix = this.form.logo.substring(markIndex);
              if (!this.fileList.length) {
                this.fileList.push({
                  name: suffix,
                  url: this.form.logo
                });
              } else {
                this.fileList = [
                  {
                    name: suffix,
                    url: this.form.logo
                  }
                ];
              }
            } else {
              this.fileList = [];
            }
            this.isUpdate = true;
          } else {
            this.isUpdate = false;
          }
        } else {
          this.$nextTick(() => {
            this.$refs['form'].resetFields();
            console.log(this.form);
          });
          this.fileList = [];

        }
      });
    }
  }
};
  </script>
  
  <style lang="less" scoped>
/*隐藏input（type=number)右边的小箭头*/
/deep/.delInput input::-webkit-outer-spin-button,
/deep/.delInput input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
/deep/.delInput input[type='number'] {
  -moz-appearance: textfield;
}
/deep/.el-textarea__inner {
  height: 150px;
}
.foodsDiv div {
  margin-left: 20px;
  margin-top: 10px;
}
.height83 {
  height: 83vh;
}
.hLabel {
  margin: 10px 0 20px;
  font-weight: 700;
  &::before {
    content: '';
    display: inline-block;
    vertical-align: top;

    margin-right: 5px;
    height: 23px;
    width: 6px;
    background-color: #1e6ceb;
  }
}
.drawer__footer {
  display: flex;
  justify-content: flex-start;
  margin-left: 15px;
}
</style>
  